package com.jugheadzhou.auth.core.webapi.handler;

import com.jugheadzhou.auth.core.common.api.Result;
import com.jugheadzhou.auth.core.common.exception.BusinessException;
import com.jugheadzhou.auth.core.common.exception.UnauthorizedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @description: 全域异常拦截
 * @author: kwb
 * @create: 2020-03-6 20:37
 **/
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class ExceptionControllerHandler {

    /**
     * 未知异常信息处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        log.error("系统错误:{}", e.getMessage(), e);
        return Result.failed("系统错误，请联系管理员");
    }

    /**
     * 业务异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> businessExceptionHandle(BusinessException e) {
        log.error("业务异常:{}", e.getDetail(), e);
        return Result.failed(e.getErrorCode(), e.getDetail());
    }

    /**
     * 拦截参数检验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return Result.validateFailed(objectError.getDefaultMessage());
    }

    /**
     * 拦截参数检验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result<?> bindExceptionHandler(BindException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return Result.validateFailed(objectError.getDefaultMessage());
    }

    /**
     * 认证异常信息处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Result unauthorizedExceptionHandler(UnauthorizedException e) {
        log.error("认证异常: {}", e.getMessage(), e);
        return Result.unauthorized(e.getMessage());
    }
}
